<template>
  <div class="home-container">
    <input
      type="text"
      placeholder="请输入城市名称"
      v-model="address"
      @input="handleInput"
    />

    <ul>
      <li v-show="res.status && res.status !== '1'">
        似乎没有找到你查找的城市
      </li>
      <li
        class="searchResults"
        v-show="res.status && res.status == '1'"
        @click="goSearchPage"
      >
        {{ resCity }}
      </li>
    </ul>
    <h2 v-if="!isExist">
      暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
    </h2>
    <StorageCity v-if="isExist && !hasSearchResults" />
    <h2 class="near" v-if="!hasSearchResults">近期天气</h2>
    <WeatherCharts />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { debounce } from 'lodash-es'
import { useWeatherStore } from '@/stores/weather.js'
import WeatherCharts from './WeatherCharts.vue'
import StorageCity from './StorageCity.vue'
import { getSearch } from '@/api'

const router = useRouter()
const store = useWeatherStore()
const { ipCity, isExist } = storeToRefs(store)

const address = ref('')
const res = ref({})
const resCity = ref('')

//路由传递参数
const goSearchPage = () => {
  router.push({
    path: '/search',
    query: {
      adcode: res.value.geocodes[0].adcode,
      city: res.value.geocodes[0].city,
    },
  })
}

//输入事件(带防抖)
const handleInput = debounce(async () => {
  if (!address.value.trim()) {
    res.value = {}
    return
  }
  res.value = await getSearch(address.value.trim())
  //   console.log(res.value)
  if (res.value.status === '1') {
    resCity.value = res.value.geocodes[0].city
  }
}, 500)

onMounted(async () => {
  await store.updateAdcode(ipCity.value)
})

//搜索
const hasSearchResults = computed(() => {
  return res.value.status == '1' // 当有有效搜索结果时返回 true
})
</script>

<style lang="scss" scoped>
.home-container {
  padding: 24px 180px;
  input {
    width: 100%;
    height: 41px;
    color: #fff;
    font-size: 18px;
    background: #00668a;
    outline: 0;
    border: none;
    border-bottom: 1px solid #fff;
    padding: 0;
    padding-left: 5px;
  }
  li {
    height: 50px;
    color: #fff;
    padding-left: 5px;
    line-height: 50px;
    margin-top: 5px;
    background: #004e71;
    &:nth-child(2) {
      cursor: pointer;
      margin-bottom: 10px;
    }
  }
  h2 {
    text-align: center;
    margin: 40px;
    color: #fff;
    &.near {
      text-align: left;
      margin-left: 0;
      margin-bottom: 10px;
    }
  }
}
</style>
